package com.leenleda.ips.util;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;

import com.leenleda.ips.MyApplication;
import com.leenleda.ips.R;
import com.leenleda.ips.activity.LoginDataActivity;
import com.leenleda.ips.activity.WebActivity;
import com.leenleda.ips.net.AEvent;
import com.leenleda.ips.receiver.Constant;
import com.leenleda.ips.util.print.NewPrintUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.leenleda.ips.receiver.Constant.*;

/**
 * JS方法提供对象
 */
public class JavaScriptObject {

    private WebActivity mainActivity;

    private String tag = "JavaScriptObject";

    public JavaScriptObject(WebActivity context) {
        mainActivity = context;
    }

    public JavaScriptObject() {

    }

    /**
     * 调用云知声进行语音合成
     * @param voiceText
     * @return
     */
    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public String PlayYZSVoice(String voiceText) {
        JSONObject object = null;
        String numStr = "";
        String dataStr = "";
        String speed = "";
        String rdn = "";
        int num = 0;
        try {
            LogUtils.e(tag, "==isSpeaking==" + TTSUtils.isSpeaking + "--voiceText--" + voiceText);

            object = new JSONObject(voiceText);
            numStr = object.optString("num");
            dataStr = object.optString("dataStr") ;
            num = Integer.parseInt(numStr);
            speed = object.optString("speed");
            rdn = object.optString("rdn");
            if (!TextUtils.isEmpty(rdn)) {
                Constant.voiceRdn = rdn;
                UShared.putString(Constant.VOICE_RDN, rdn);
            }
            if (!TextUtils.isEmpty(speed)){
                Constant.voiceSpeed = speed;
                UShared.putString(Constant.VOICE_SPEED, speed);
            }
            TTSUtils.getInstance().speak(mainActivity, dataStr, num);
            if (TTSUtils.isSpeaking)
                return "speaking";
            return "success";
        } catch (Exception e) {
            TTSUtils.getInstance().speak(mainActivity, voiceText, 1);
            if (TTSUtils.isSpeaking)
                return "speaking";
            return "success";
        }
    }

    private List<String> voiceCache = new ArrayList<>();

    /**
     *
     * 添加发声缓存
     */
    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public String playVoiceAdd(String voiceText) {
        voiceCache.add(voiceText);
        LogUtils.e(tag, "==playVoiceAdd====voiceText=" + voiceText);
        return "success";
    }

    /**
     * 获取发声缓存
     */
    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public String playVoiceGet() {
        String result = "fail";
        if (voiceCache.size() > 0)
            result = voiceCache.get(0);
        LogUtils.e(tag, "==playVoiceGet====result=" + result + ",voiceCache=" + voiceCache);
        return result;
    }

    /**
     *
     * 删除发声缓存
     */
    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public boolean playVoiceDelete(String voiceText) {
        boolean result = false;
        if (voiceCache.size() > 0)
            result = voiceCache.remove(voiceText);
        LogUtils.e(tag, "==playVoiceDelete=====result==" + result + ",voiceCache=" + voiceCache);
        return result;
    }

    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void playDi() {
        mainActivity.playBee(R.raw.voice_ding);
    }

    /**
     * 关闭页面自动刷新
     * @return
     */
    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public String CloseRefresh() {
        UShared.putString(Constant.WebViewRefreshStatus, "false");
        return "success";
    }

    /**
     * 开启页面自动刷新
     */
    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public String OpenRefresh() {
        UShared.putString(Constant.WebViewRefreshStatus, "true");
        return "success";
    }

    /**
     * 设置缓存
     * @param key 设置的键名
     * @param value 设置的值
     * @return 设置结果
     */
    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public String SetCache(String key, String value) {
        UShared.putString(key, value);
        return "success";
    }
    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void printAgain(String cmdStr, int cutter) {//新的打印机(非)
        LogUtils.e(tag, "==printerData=====" + cmdStr);
        String state = NewPrintUtil.getInstance(mainActivity).printerTest(cmdStr,cutter);
        if (!Utils.isEmpty(state)){
            AEvent.notifyListener(AEvent.TO_TOAST, true, state);
            TTSUtils.getInstance().speak(mainActivity, state, 1);
        }
    }

    /**
     * 获取缓存
     * @param key 设置的键名
     * @return  缓存值
     */
    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public String GetCache(String key) {
        return UShared.getString(key);
    }

    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void readCard(int state) {
        LogUtils.e(tag, "==readCard==state1===" + state + ",bb=" + mainActivity.readState);
        if (mainActivity.readState){//正在读取中
            long time = System.currentTimeMillis();
            int from = (int) ((time - mainActivity.readTime) / 1000);
            LogUtils.e(tag, "==readCard==time1===" + time );
            LogUtils.e(tag, "==readCard==time2===" + mainActivity.readTime );
            if (from > 2){//等待时间超过5S时，允许重新读取
            } else {//等候5s读取时间
                return;
            }
        }
        LogUtils.e(tag, "==readCard==state2===" + state + ",bb=" + mainActivity.readState);
        mainActivity.readState = true;
        mainActivity.readTime = System.currentTimeMillis();
        try {
            switch (state){
                case 0:
                    mainActivity.openUSB();
//                    new Handler().post(() -> mainActivity.openUSB());
                    break;
                case 1:
                    mainActivity.readM1Card();
                    break;
                case 2:
                    mainActivity.readSecure();
                    break;
                case 3:
                    mainActivity.readIDCard();
                    break;
                case 5:
                    mainActivity.readCardSDT();
                    break;
            }
        } catch (Exception e){
            LogUtils.e(tag, "==readCard==e===" + e.getMessage());
        }
    }

    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void readCardLoop(int allTime, int state, int fromTime) {//allTime 持续等待时间(单位秒)， state 类型  ， fromTime 每次读卡间隔时间(单位秒)
        LogUtils.e(tag, "==readCard==allTime===" + allTime + ",fromTime=" + fromTime);
        mainActivity.oneAutoCard(allTime, state, fromTime);
    }

    /**
     * # state 0, 1, 2, 3
     * # time  时间间隔 time <= 0 暂停
     */
    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void autoCard(int state, int time) {
        mainActivity.overTime = 0;
        mainActivity.autoCard(state, time);
    }

    /**
     * webView GC 重新加载
     */
    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void webViewGC() {
        long currentTime = System.currentTimeMillis();
        long upTime = UShared.getLong("webViewGC", 0);
        LogUtils.e(tag, "=JavascriptInterface==webViewGC===2==" + upTime);
        if (currentTime - upTime < 60 * 1000)
            return;
        LogUtils.e(tag, "=JavascriptInterface==webViewGC===1==" + currentTime);
        mainActivity.webViewGC(2);
    }

    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void deviceControl(int state){
        switch (state){
            case 1://关机
                sendDeviceControl(DEVICE_DOWN, state);
                break;
            case 2://重启
                sendDeviceControl(DEVICE_RESTART, state);
                break;
            default://定时开关机
                if (state < 120)
                    state = 120;
                sendDeviceControl(DEVICE_REOPEN, state);
//                Devices.getInstance().openTime(true, state);
                break;
        }
    }

    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void setLamp(int pos, int state){
        LogUtils.e("SLKVNSDV", "=====setLamp===pos==" + pos + ",res=" + state);
        sendCon(DEVICE_LAMP, pos, state);
    }

    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void setVoice(int state){//1~100
        if (state < 0 || state > 100){
            TTSUtils.getInstance().speak(mainActivity, "声音设置范围为1～10", 1);
            return;
        }
//        Utils.voiceSet(mainActivity, state);
        sendDeviceControl(DEVICE_VOICE_SET, state);
    }

    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void setLight(int bright){//1~100
        if (bright < 0 || bright > 100){
            TTSUtils.getInstance().speak(mainActivity, "亮度设置范围为1～100", 1);
            return;
        }
        mainActivity.mHandler.post(() -> {
            Window localWindow = mainActivity.getWindow();
            WindowManager.LayoutParams localLayoutParams = localWindow.getAttributes();
            float f = bright / 100.0F;
            localLayoutParams.screenBrightness = f;
            localWindow.setAttributes(localLayoutParams);
        });
    }

    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void voiceChange(int state){
        LogUtils.e("LFSDGSD", "======state====" + state);
//        Utils.voiceChange(mainActivity, state);
        sendDeviceControl(DEVICE_VOICE_CHANGE, state);
    }

    /**
     * webView GC 重新加载
     */
    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void toSysInfo() {
        Intent intent = new Intent(mainActivity, LoginDataActivity.class);
        Utils.startActivity(mainActivity, intent);
    }

    public static int SHOW_TIME_LOOP = 0;

    public static void sendDeviceControl(int state, int result){
        LogUtils.e("SLKVNSDV", "=====state=====" + state);
        Intent intent = new Intent(RECEIVER);
        Bundle bundle = new Bundle();
        bundle.putInt("state", state);
        bundle.putInt("result", result);
        intent.putExtras(bundle);
        MyApplication.getInstance().sendBroadcast(intent);
    }
    private static final String RECEIVER = "com.leld.updatetool.serve.ReceiverMsg";//更新工具接受消息广播


    public static void sendCon(int state, int pos, int res){
        LogUtils.e("SLKVNSDV", "=====state=====" + state + ",pos=" + pos + ",res=" + res);
        Intent intent = new Intent(RECEIVER);
        Bundle bundle = new Bundle();
        bundle.putInt("state", state);
        bundle.putInt("pos", pos);
        bundle.putInt("res", res);
        intent.putExtras(bundle);
        MyApplication.getInstance().sendBroadcast(intent);
    }
}
